package SplineEngine
{
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
		
	public class SplineModule
	{
		private var moduleName_string:String;
		private var modulePath_string:String;
		//private var homePage_object:Object;
		private var splineEngineModel_object:Object;
		private var infoPacket_object:Object=new Object;
		
		private var moduleXml_file:File;
		
		private var lessonName_array:Array = new Array;
		private var lessonDiscription_array:Array = new Array;
		private var relativeLessonPath_array:Array = new Array;
		private var lessonPath_array:Array = new Array;
		private var lessonEditPass_array:Array = new Array;
		private var lessonInstructorPass_array:Array = new Array;
		
		public function SplineModule(name:String, path:String/*,infoObj_object:Object*/,splineEngine:Object)
		{
			this.moduleName_string = name;
			this.modulePath_string = path;
			//this.homePage_object = homePageObject;
			//this.infoPacket_object = infoObj_object;
			this.splineEngineModel_object = splineEngine;
			this.loadModule();
		}
		
		
		//--------------------------------- Module.xml handler functions -------------------------------------------//
		public function loadModule():void
		{
			var urlLoader:URLLoader = new URLLoader;
			//var file:File=new File(this.modulePath_string+"/"+this.moduleName_string+".xml");
			this.moduleXml_file = new File(this.modulePath_string+"/"+this.moduleName_string+".xml");
			var urlRequest:URLRequest = new URLRequest(this.moduleXml_file.nativePath);
			trace(this.modulePath_string+"/"+this.moduleName_string+".xml");
			trace(this.moduleXml_file.nativePath);
			urlLoader.load(urlRequest);
			urlLoader.addEventListener(Event.COMPLETE,this.moduleLoadingComplete);
		}
		
		private function moduleLoadingComplete(event:Event):void
		{
			trace("Before module loading completion"+this.lessonName_array);
			
			var moduleXml:XML = new XML(event.target.data);
			var index:int=0;
			for each(var node:XML in moduleXml.Lesson)
			{
				this.lessonName_array[index]=node.@name.toString();
				this.lessonDiscription_array[index]=node.@discription.toString();
				this.relativeLessonPath_array[index]=node.@path.toString();
				this.lessonPath_array[index]=this.modulePath_string+node.@path.toString();
				this.lessonEditPass_array[index]=node.@editPassword.toString();
				this.lessonInstructorPass_array[index]=node.@instructorPassword.toString();
				index++;
				/*this.lessonName_array.push(node.@name.toString());
				this.lessonDiscription_array.push(node.@discription.toString());
				this.lessonPath_array.push(node.@path.toString());
				this.lessonEditPass_array.push(node.@editPassword.toString());
				this.lessonInstructorPass_array.push(node.@instructorPassword.toString());*/
				
			}
			trace("event = "+event);
			trace ("event.target = "+event.target);
			trace("event.target.data = "+event.target.data);
			trace ("LessonPath Array :"+this.lessonPath_array);
			//var file:File = new File(event.target);
			//this.moduleXml_file.addEventListener(Event.CANCEL,this.interpretUserMessage);
			//this.moduleXml_file.cancel();
			//this.interpretUserMessage();
			this.openModule();
			trace("After module loading completion "+this.lessonName_array);
			trace(this.moduleName_string+".xml loaded in local arrays");
		}
		
		private function updateModuleXML():void
		{
			//var moduleXml_file:File = new File(this.modulePath_string+"/"+this.moduleName_string+".xml");
			var moduleXml_xml:XML = new XML(<Module></Module>);
			
			for(var i:int=0; i<this.lessonName_array.length; i++)
			{
				var node:XML = new XML(<Lesson></Lesson>);
				node.@name = this.lessonName_array[i];
				node.@discription = this.lessonDiscription_array[i];
				//node.@path = this.lessonPath_array;
				node.@path=this.relativeLessonPath_array[i];
				node.@editPassword = this.lessonEditPass_array[i];
				node.@instructorPassword = this.lessonInstructorPass_array[i];
				moduleXml_xml.appendChild(node);
			} 
			
			this.writeXmlFile(this.moduleXml_file, moduleXml_xml);
		}
		
		private function writeXmlFile(file:File, xml:XML):void
		{
			var fileStream:FileStream = new FileStream;
			//file.cancel();
			//file.addEventListener(Event.CANCEL,writeFile)
			fileStream.open(file, FileMode.WRITE);
			fileStream.writeUTFBytes(xml.toXMLString());
			fileStream.close();
			trace(file.nativePath.toString());
		}
		//--------------------------------------------------------------------------------------------------------------//
		
		//---------------------------------------communication functions ------------------------------------------------//
		public function interpretUserMessage(infoObj:Object):void
		{
			this.infoPacket_object=infoObj;
			var message:String = this.infoPacket_object.message.toString();
			
			switch(message)
			{
				case "createNewLesson":
						trace("creating new lesson");
						this.openModule();
						this.createNewLesson();
						break;
				case "editLessonMetadata":
						trace("edit lesson metadata");
						this.editLessonMetadata();
						break;
				case "deleteLesson":
						trace("deleting selected lesson");
						this.removeLesson();
						break;
				case "openModule":
						trace("opening selected lesson");
						this.openModule();
						break;
				default :
						trace("No matching service available");
	
			}
		}
		
		
		
		private function sendLessonDataModel(selectedLessonIndex:int):void
		{
			var infoObj_object:Object=new Object;
			infoObj_object.message = "refreshLessonListDataModel";
			infoObj_object.lessonName_array = this.lessonName_array;
			infoObj_object.lessonDiscription_array = this.lessonDiscription_array;
			infoObj_object.lessonPath_array = this.lessonPath_array;
			infoObj_object.lessonEditPass_array =this.lessonEditPass_array;
			infoObj_object.lessonInstructorPass_array = this.lessonInstructorPass_array;
			infoObj_object.selectedLessonIndex = selectedLessonIndex;
			trace("in sendLessonDataModel : "+this.lessonName_array);
			//return infoObj_object;
			this.outgoingMessageGateway(infoObj_object);
		}
		
		private function outgoingMessageGateway(infoObj_object:Object):void
		{
			this.splineEngineModel_object.sendNotificationToObservers(infoObj_object);
			
		}
		
		//--------------------------------------------------------------------------------------------------------------//
		
		//-----------------------Open Existing Module ------------------------------------------------------------------// 
		public function openModule():void
		{ 
			//this.loadModule();
			
			var selectedLessonIndex:int = 0;
			this.sendLessonDataModel(selectedLessonIndex);
		}
		//-------------------------------------------------------------------------------------------------------------//
		
		//-------------------------------------------editLessonMetadata------------------------------------------------//
		
			
		public function editLessonMetadata():void
		{
			var index:int=this.infoPacket_object.selectedLessonIndex;
			
			this.lessonName_array[index]=this.infoPacket_object.name.toString();
			this.lessonDiscription_array[index]=this.infoPacket_object.discription.toString();
			this.lessonEditPass_array[index]=this.infoPacket_object.editPass.toString();
			this.lessonInstructorPass_array[index]= this.infoPacket_object.instructorPass.toString();
			
			this.sendLessonDataModel(index);
			this.updateModuleXML();
			
		}
		//--------------------------------------------------------------------------------------------------------------//
		
		//-----------------------------------------remove lesson -------------------------------------------------------//
		public function removeLesson():void
		{
			//this.loadModule();
			var index:int = this.infoPacket_object.selectedLessonIndex;
			
			if(this.infoPacket_object.completeRemoval)
			{
				var file:File = new File(this.lessonPath_array[index].toString());
				file.moveToTrash();
			}
			this.lessonName_array.splice(index,1);
			this.lessonDiscription_array.splice(index,1);
			this.lessonPath_array.splice(index,1);
			this.relativeLessonPath_array.splice(index,1);
			this.lessonEditPass_array.splice(index,1);
			this.lessonInstructorPass_array.splice(index,1);
						
			this.sendLessonDataModel(this.lessonName_array.length - 1);
			this.updateModuleXML();
			
		}
		//---------------------------------------------------------------------------------------------------------------//
		//-------------------------------- create new lesson ------------------------------------------------------------//
		public function createNewLesson():void
		{
			//this.loadModule();
			
			var searchObj_object:Object = new Object;
			searchObj_object = this.checkLessonExistance(this.infoPacket_object.name.toString());
			if(searchObj_object.exists.toString() == "true")
			{
				this.outgoingMessageGateway(searchObj_object);
				return;
			}
			
			trace("this.lessonName_array = "+this.lessonName_array);
			this.lessonName_array.push(this.infoPacket_object.name.toString());
			trace("this.lessonName_array = "+this.lessonName_array);
			this.lessonDiscription_array.push(this.infoPacket_object.discription.toString());
			this.lessonEditPass_array.push(this.infoPacket_object.editPass.toString());
			this.lessonInstructorPass_array.push(this.infoPacket_object.instructorPass.toString());
			
			trace(this.modulePath_string+"/"+this.infoPacket_object.name.toString());
			
			var newLesson_file:File = new File(this.modulePath_string+"/"+this.infoPacket_object.name.toString());
			newLesson_file.createDirectory();
			this.lessonPath_array.push(newLesson_file.nativePath.toString());
			this.relativeLessonPath_array.push("/"+this.infoPacket_object.name.toString());
			trace("################## =========>lessonPath_array = "+this.lessonPath_array);
			var newLessonSpline_file:File = new File(newLesson_file.nativePath.toString()+"/"+this.infoPacket_object.name.toString()+".spml");
			var fileStream:FileStream=new FileStream;
			fileStream.open(newLessonSpline_file, FileMode.WRITE);
			fileStream.writeUTFBytes(this.infoPacket_object.name.toString());
			fileStream.close();
			
			
			var newLessonXml_file:File = new File(newLesson_file.nativePath.toString()+"/"+this.infoPacket_object.name.toString()+".xml");
			var newLessonXml_xml:XML = new XML(<Lesson></Lesson>);
			newLessonXml_xml.@name = this.lessonName_array[this.lessonName_array.length-1];
			newLessonXml_xml.@discription = this.lessonDiscription_array[this.lessonDiscription_array.length -1];
			newLessonXml_xml.@editPassword = this.lessonEditPass_array[this.lessonEditPass_array.length-1];
			newLessonXml_xml.@instructorPassword = this.lessonInstructorPass_array[this.lessonInstructorPass_array.length-1];
			
			this.writeXmlFile(newLessonXml_file, newLessonXml_xml);
			trace(newLessonXml_file.name.toString()+"created");
			
			this.sendLessonDataModel(this.lessonName_array.length - 1);
			this.updateModuleXML();
			
		}
		
		private function checkLessonExistance(lessonName:String):Object
		{
			var infoObj_object:Object= new Object;
			var index:int=0;
			for each(var name:String in this.lessonName_array)
			{
				if(lessonName==name)
				{
					infoObj_object.exists = "true";
					infoObj_object.index = index;
					infoObj_object.message = "Alert";
					infoObj_object.type = "Error";
					infoObj_object.info = "Error : A lesson with same name already exists, use another name";
					return infoObj_object;
				}
				index++ ;
			}
			
			infoObj_object.exists = "false";
			return infoObj_object;
		}
		
		//----------------------------------------------------------------------------------------------------------------------------//
	}
}